package com.shanhesoft.java.common.ws;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.shanhesoft.java.modules.exam.domain.vo.OjSubmissionsVo;
import com.shanhesoft.java.modules.exam.service.OjSubmissionsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/a/submissionWs/{submissionId}")
@Component
public class SubmissionWebSocketServer {

	static Log log=LogFactory.get(SubmissionWebSocketServer.class);
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,Session> WEB_SOCKET_MAP = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String,String> LOST_MSG = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
//    private Session session;
    /**接收userId*/
    private String submissionId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("submissionId") String submissionId) {
    	log.info(submissionId + "建立连接！");
//        this.session = session;
        this.submissionId=submissionId;
        if(WEB_SOCKET_MAP.containsKey(submissionId)){
            WEB_SOCKET_MAP.remove(submissionId);
            WEB_SOCKET_MAP.put(submissionId,session);
            //加入set中
        }else{
            WEB_SOCKET_MAP.put(submissionId,session);
        }
		String msg = LOST_MSG.get(submissionId);
		try {
			if(StrUtil.isNotEmpty(msg)){
				session.getBasicRemote().sendText(msg);
				LOST_MSG.remove(submissionId);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(WEB_SOCKET_MAP.containsKey(submissionId)){
            WEB_SOCKET_MAP.remove(submissionId);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("提交编号:"+submissionId+",报文:"+message);
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("提交编号:"+this.submissionId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message, @PathParam("submissionId") String submissionId) throws IOException {
		log.info("发送消息到:"+submissionId+"，报文:"+message);
		if(StringUtils.isNotBlank(submissionId)&&WEB_SOCKET_MAP.containsKey(submissionId)){
			WEB_SOCKET_MAP.get(submissionId).getBasicRemote().sendText(message);
		}else{
			log.error("用户"+submissionId+",不在线！");
			String msg = LOST_MSG.get(submissionId);
			if(StrUtil.isNotEmpty(msg)){
				msg = msg +"\n" +message;
			}else {
				msg = message;
			}
			LOST_MSG.put(submissionId, msg);
		}
    }


    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message, String submissionId) throws IOException {
        log.info("发送消息到:"+submissionId+"，报文:"+message);
        if(StringUtils.isNotBlank(submissionId)&&WEB_SOCKET_MAP.containsKey(submissionId)){
            WEB_SOCKET_MAP.get(submissionId).getBasicRemote().sendText(message);
        }else{
        	String error = "用户"+submissionId+",不在线！\t消息内容："+message;
            log.error(error);
			String msg = LOST_MSG.get(submissionId);
			if(StrUtil.isNotEmpty(msg)){
				msg = msg +"\n" +message;
			}else {
				msg = message;
			}
			LOST_MSG.put(submissionId, msg);
        }
    }

}
